package com.stars.easyms.datasource.mybatis.transaction;

import com.stars.easyms.datasource.EasyMsDataSource;
import com.stars.easyms.datasource.EasyMsMultiDataSource;
import com.stars.easyms.datasource.holder.EasyMsSynchronizationManager;
import com.stars.easyms.datasource.transaction.EasyMsTransactionSynchronizationManager;
import org.apache.ibatis.session.TransactionIsolationLevel;
import org.apache.ibatis.transaction.Transaction;
import org.mybatis.spring.transaction.SpringManagedTransaction;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;

import javax.sql.DataSource;

/**
 * <p>className: EasyMsSpringManagedTransactionFactory</p>
 * <p>description: EasyMs自定义事务工厂类</p>
 *
 * @author guoguifang
 * @date 2019-10-15 13:44
 * @since 1.3.3
 */
public final class EasyMsSpringManagedTransactionFactory extends SpringManagedTransactionFactory {

    @Override
    public Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) {
        // 如果处于事务中时此时已经可以得到具体的EasyMsDataSource
        if (EasyMsTransactionSynchronizationManager.isSynchronizationActive()) {
            EasyMsDataSource easyMsDataSource = EasyMsSynchronizationManager.getEasyMsDataSource();
            if (easyMsDataSource != null) {
                return new EasyMsSpringManagedTransaction(easyMsDataSource);
            }
            if (dataSource == null) {
                throw new IllegalStateException("No EasyMsDataSource specified in easy-ms transaction!");
            }
        }
        return newTransaction(dataSource);
    }

    private Transaction newTransaction(DataSource dataSource) {
        if (dataSource instanceof EasyMsMultiDataSource) {
            return new EasyMsSpringManagedTransaction((EasyMsMultiDataSource) dataSource);
        }
        return new SpringManagedTransaction(dataSource);
    }

}